package com.apestech.framework.sql.condition;

import com.apestech.framework.sql.MultiDataBase;
import com.apestech.framework.sql.modul.FromList;

/**
 * ERP权限子串解析，对应岗位ID由外部带入
 * @author hupo
 *
 */
public class RoleExpression {

	private FromList fromtab;
	private String roleField;  //权限字段
	private String fieldName;  //单据字段
	private String alias;   //单据别名
	private String roleValue=null;   //带，分隔符的权限字串，仅适用于ORACLE模式
	private String roleTable="QX_CZ_CKKQID";   //"AUT_ORGANIZATIONS";   //权限表名
	private String head;
	private String tail;
	private String postField="BDQXID";
	private boolean tree=false;
	private String dbType="ORACLE";
	private String sql;
	
	/*
	 EXISTS ( SELECT 1 FROM QX_CZ_CKKQID WHERE BDQXID='1001A0011' AND WAR_CGRKD.CKKQID=QX_CZ_CKKQID.CKKQID)
	 
	 EXISTS ( 
	    SELECT 1 FROM TABLE (
	      SYS_split('1001A0010011;1001A0010012;1001A0010013;1001A0010014;1001A0010015;1001A0010016;1001A0010017',';')
	    )
        WHERE WAR_CGRKD.CKKQID LIKE COLUMN_VALUE||'%'
     )
     
     //要增加如没有配权限代表为全部权限功能。。。。。。。
     
	 */
	
	public RoleExpression(String dbType, String roleField, String fieldName, String alias, String postId){
		this.dbType=dbType;
		this.roleField=roleField;
		this.fieldName=fieldName;
		this.alias=alias;
		this.head=" EXISTS ( SELECT 1 FROM ";
		this.tail=")";
	}
	
	public void setRoleValue(String roleValue){
		this.roleValue=roleValue;
	}
	
	public void setRoleTable(String roleTable){
		this.roleTable=roleTable;
	}
	
	public String getSql(){
		return this.sql;
	}
	
	private String getTabName(){
		if(this.roleValue!=null){
			return "TABLE (SYS_SPLIT('"+this.roleValue+"',',') ) AS SYS_ROLE ";
		} else {
			return this.roleTable+" AS SYS_ROLE ";
		}
	}
	
	private String getWhere(){
		if(this.roleValue!=null){
			return " where ";
		} else {
			return " where SYS_ROLE."+this.postField+"=#{"+this.postField+"} and ";
		}
	}
	
	private String getWhereValue(){
		MultiDataBase db=new MultiDataBase(this.dbType);
		if(tree){
			if(this.roleValue!=null){
				return this.alias+this.fieldName+" like "+db.getStringConcat("SYS_ROLE.COLUMN_VALUE","'%'");
			} else {
				return this.alias+this.fieldName+" like "+db.getStringConcat("SYS_ROLE."+this.roleField,"'%'");
			}
		} else {
			if(this.roleValue!=null){
				return this.alias+this.fieldName+"=SYS_ROLE.COLUMN_VALUE";
			} else {
				return this.alias+this.fieldName+"=SYS_ROLE."+this.roleField;
			}
		}
	}
	
	public void expain(){
		this.sql=this.head;
		this.sql=this.sql+getTabName();
		this.sql=this.sql+getWhere();
		this.sql=this.sql+getWhereValue();
		this.sql=this.sql+this.tail;
		//this.sql="("+this.sql+")";
	}

}
